<script setup lang="ts">
import { onMounted, onUnmounted } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { Toast } from "antd-mobile";
import { useRouter } from "vue-router";
import {useStore} from "../store";


// export default defineComponent({
//   name: 'map',
  
// })
let map:any = null;
let router = useRouter()
let useContents=useStore()

declare global {
  interface Window {
    _AMapSecurityConfig?: {
      securityJsCode: string;
    };
  }
}

onMounted(() => {
  window._AMapSecurityConfig = {
    securityJsCode: "a7333bd507b8d3d41c7ded8c06dcef37",
  };
  
  AMapLoader.load({
    key: "06bf3c8dee141cb0ad1c0ce26fdb5353", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.Geocoder"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  })
    .then((AMap) => {
      map = new AMap.Map("container", {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 18, // 初始化地图级别
        center: [115.488968, 38.815083], // 初始化地图中心点位置
      });
      map.on("click", function (ev:any) {
        //触发事件的对象
        // var target = ev.target;
        //触发事件的地理坐标，AMap.LngLat 类型
        var lnglat = ev.lnglat;
        //触发事件的像素坐标，AMap.Pixel 类型
        // var pixel = ev.pixel;
        //触发事件类型
        // var type = ev.type;
        // console.log(getAddrByLatLng(lnglat.lng,lnglat.lat,AMap))
        getAddrByLatLng(lnglat.lng, lnglat.lat, AMap).then((address:any) => {
          // console.log('Address:', address);
          useContents.$patch({address:`${address.province + ' ' + address.city + ' ' + address.district + ' ' + address.township}`})
          Toast.show(`${address.province + ' ' + address.city + ' ' + address.district + ' ' + address.township}`)
          router.go(-1)
        }).catch(error => {
          console.error('Error:', error.message);
        });
        // console.log(lnglat)
      });
      const getAddrByLatLng = async (lng:any, lat:any, AMap:any) => {
      return new Promise((resolve, reject) => {
        if (!AMap || !AMap.Geocoder) {
          reject(new Error('AMap or AMap.Geocoder is not loaded'));
          return;
        }

        // 检查经纬度的有效性
        if (!isValidLatLng(lng, lat)) {
          reject(new Error('Invalid latitude or longitude'));
          return;
        }

        const geocoder = new AMap.Geocoder({
          city: '全国', // 默认为全国范围
        });

        // 逆地理编码
        geocoder.getAddress([lng, lat], function(status:any, result:any) {
          if (status === 'complete' && result.info === 'OK') {
            // 获取省、市、区、街道信息
            const addressComponent = result.regeocode.addressComponent;
            const province = addressComponent.province;
            const city = addressComponent.city || addressComponent.province; // 如果是直辖市，city 和 province 相同
            const district = addressComponent.district;
            const township = addressComponent.township;
            // console.log(addressComponent)
            resolve({ province, city, district, township });
          } else {
            // 更详细的错误信息
            const errorMessage = `Failed to get address: ${result.info || status}`;
            console.error(errorMessage, result);
            reject(new Error(errorMessage));
          }
        }, {
          extensions: 'all' // 获取完整的地址信息
        });
      });
    };

    const isValidLatLng = (lng:any, lat:any) => {
      return (
        typeof lng === 'number' &&
        typeof lat === 'number' &&
        !isNaN(lng) &&
        !isNaN(lat) &&
        lng >= -180 &&
        lng <= 180 &&
        lat >= -90 &&
        lat <= 90
      );
    };
    })
    .catch((e) => {
      console.log(e);
    });
});

onUnmounted(() => {
  map?.destroy();
});
</script>

<template>
  <div id="container" style="z-index: 2;"></div>
</template>

<style scoped>
#container {
  width: 100%;
  height: 100vh;
}
</style>
